import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/signService.dart';
import 'package:xiaomi_shop/app/services/userService.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/index.dart';

class AddressListController extends GetxController {
  RxList addressList = [].obs;
  @override
  void onInit() {
    super.onInit();
    getAddressList();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 获取收货地址列表
  getAddressList() async {
    UserModel? user = await UserService.getUser();
    Map tempJson = {
      "uid": user?.id,
    };
    // 获取签名
    String sign = SignService.sign({...tempJson, "salt": user?.salt});
    var response = await XHttp.getInstance()
        .get(Api.addressList, {...tempJson, "sign": sign});
    if (response != null) {
      Result result = response as Result;
      if (result.data["result"] != null) {
        List tempList = result.data["result"];
        List<AddressItemModel> list = [];
        for (var element in tempList) {
          list.add(AddressItemModel.fromJson(element));
        }
        addressList.value = list;
      }
    } else {
      Toast.show("网络错误", type: Toast.ERROR);
    }
  }

  // 修改默认收货地址
  changeDefaultAddress(String addressId) async {
    UserModel? user = await UserService.getUser();
    Map tempJson = {"uid": user?.id, "id": addressId};
    // 获取签名
    String sign = SignService.sign({...tempJson, "salt": user?.salt});
    var response = await XHttp.getInstance()
        .post(Api.changeDefaultAddress, {...tempJson, "sign": sign});
    if (response != null) {
      Result result = response as Result;
      if (result.data["success"]) {
        await getAddressList();
        Toast.show("修改成功");
        Get.back();
      } else {
        Toast.show(result.msg, type: Toast.ERROR);
      }
    } else {
      Toast.show("网络错误", type: Toast.ERROR);
    }
  }

  // 删除收货地址
  deleteAddress(String addressId) async {
    UserModel? user = await UserService.getUser();
    Map tempJson = {"uid": user?.id, "id": addressId};
    // 获取签名
    String sign = SignService.sign({...tempJson, "salt": user?.salt});
    var response = await XHttp.getInstance()
        .post(Api.deleteAddress, {...tempJson, "sign": sign});
    if (response != null) {
      Result result = response as Result;
      if (result.data["success"]) {
        await getAddressList();
        Toast.show("删除成功");
        Get.back();
      } else {
        Toast.show(result.msg, type: Toast.ERROR);
      }
    } else {
      Toast.show("网络错误", type: Toast.ERROR);
    }
  }
}
